import redisHelper from "./redisHelper.js"
import db from "./mysqlHelper.js"
import returnData from "./response.js"
import moment from "moment";
import md5 from "md5"
import logger from "./logger.js";
import jsonwebtoken from "jsonwebtoken"
import response from './response.js';



function ojbectSort(obj) {
    let temp = Object.keys(obj).sort();
    let temp2 = '';
    for (let index = 0; index < temp.length; index++) {
        if (temp[index] != 'sign' && typeof (obj[temp[index]]) != 'object') temp2 += temp[index] + '=' + obj[temp[index]] + '&';
    }
    return temp2;
}

function sign(app, data) {
    let str = ojbectSort(data);
    str += 'secret=' + app.secret;
    return returnData.success(md5(str));

}

const whiteList = ['/oper/login', '/images','/oper/insert','/getOpenId'];

async function auth(ctx, next) {
    const url = ctx.url;
   // console.log('url:', url);
    //直接放行
    // if (url.startsWith(`/service/Api/Token/Get`)) {
    //     await next();
    //     return;
    // } 
    // //对外接口accessToekn认证
    // else if (url.startsWith(`/service/Api/`) || url.startsWith(`/service/Api/`)) {
    //     let accessToekn = ctx.header.authorization;
    //     if (accessToekn == null) {
    //         ctx.body = returnData.fail("accessToekn无效");
    //         return;
    //     }
    //     try {
    //         let app = jsonwebtoken.verify(accessToekn, 'leimong');
    //         ctx.state.enterprise = app;
    //         await next();
    //         return;

    //     } catch (err) {
    //         ctx.body = returnData.fail("accessToekn无效");
    //         return;
    //     }
    // }
    // 登录验证白名单
    let arr = whiteList.filter((x) => url.indexOf(x) > -1);
    if (arr.length > 0) {
        await next();
        return;
    }
    // 登录验证
    let token = ctx.header.token || '';
    console.log('token:', token);
    if (token == '') {
        ctx.body = response.fail('请先登录');
        return;
    }
    try {
        let obj = jsonwebtoken.verify(token, secret);
        ctx.state.oper = obj;
    } catch (err) {
        ctx.body = response.fail('登录已过期,请重新登录');
        return;
    }
    await next();
}

const secret = 'token_secret_key';
/**
  *  生成token
  * @param {*} params
  * @returns
  */
async function createToken(params) {
    let token = await jsonwebtoken.sign(params, secret, {
        expiresIn: '2h',
    });
    return { token, expireTime: moment().add(2, 'h').unix() };
}


function generatePwd(pwd) {
    return md5(pwd);
}

export { auth, createToken, generatePwd }